<?php
/**
 * Member administration interface, based on ModelAdmin
 * @package site
 */
class MemberAdmin extends ModelAdmin {

    private static $url_segment = 'member';
    private static $menu_title = 'Member';
    private static $menu_icon = 'member/images/member-icon.png';
	public $showImportForm = false;

    private static $managed_models = array(
    	'Member'
    );
	
	public function getEditForm($id = null, $fields = null) {
        $list = $this->getList();
        $exportButton = new GridFieldExportButton('buttons-after-left');
        $exportButton->setExportColumns($this->getExportFields());
        
		if($this->modelClass == 'Member'){
			$listField = GridField::create(
	            $this->sanitiseClassName($this->modelClass),
	            false,
	            $list,
	            $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))
					->removeComponentsByType('GridFieldDetailForm')
	                ->removeComponentsByType('GridFieldFilterHeader')
	                ->addComponents(new MemberGridFieldDetailForm(), new GridFieldLoginButton(), new MemberGridFieldStatusAction(), new GridFieldButtonRow('after'), new GridFieldPrintButton('buttons-after-left'), $exportButton)
	        );
		
		}
		else{
	        $listField = GridField::create(
	            $this->sanitiseClassName($this->modelClass),
	            false,
	            $list,
	            $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))
	                ->removeComponentsByType('GridFieldFilterHeader')
	                ->addComponents(new GridFieldButtonRow('after'), new GridFieldPrintButton('buttons-after-left'), $exportButton)
	        );
		}
        
		// Validation
        if(singleton($this->modelClass)->hasMethod('getCMSValidator')) {
            $detailValidator = singleton($this->modelClass)->getCMSValidator();
			if($this->modelClass == 'Member'){
				$listField->getConfig()->getComponentByType('MemberGridFieldDetailForm')->setValidator($detailValidator);
			}
			else{
            	$listField->getConfig()->getComponentByType('GridFieldDetailForm')->setValidator($detailValidator);
			}
        }
		
		$note = new LiteralField('MembersCautionText',
			sprintf('<p class="caution-remove"><strong>%s</strong></p>',
				_t(
					'MemberAdmin.MemberListCaution', 
					'Caution: Removing members from this list will remove them from all groups and the'
						. ' database'
				)
			)
		);

        $form = CMSForm::create( 
            $this,
            'EditForm',
            new FieldList($listField, $note),
            new FieldList()
        )->setHTMLID('Form_EditForm');
		$form->setResponseNegotiator($this->getResponseNegotiator());
        $form->addExtraClass('cms-edit-form cms-panel-padded center');
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
        $editFormAction = Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'EditForm');
        $form->setFormAction($editFormAction);
        $form->setAttribute('data-pjax-fragment', 'CurrentForm');

        $this->extend('updateEditForm', $form);
        
        return $form;
    }

	public function getSearchContext() {
		$context = singleton($this->modelClass)->getDefaultSearchContext();
		$context->addField(TextField::create('JoinedYear', _t('MemberAdmin.JOINED_YEAR', 'Joined Year')));
		// Namespace fields, for easier detection if a search is present
		foreach($context->getFields() as $field) $field->setName(sprintf('q[%s]', $field->getName()));
		foreach($context->getFilters() as $filter) $filter->setFullName(sprintf('q[%s]', $filter->getFullName()));

		$this->extend('updateSearchContext', $context);

		return $context;
	}

	public function getList() {
		$context = $this->getSearchContext();
		$params = $this->request->requestVar('q');
		$list = $context->getResults($params);
		
		if($this->modelClass == 'Member'){
			$list = $list->filter('IsDistributor', 1);
			if(isset($params['JoinedYear']) && $params['JoinedYear']){
				$filter = YearMatchFilter::create('JoinedDate');
				$filter->setModel($this->modelClass);
				$filter->setValue($params['JoinedYear']);
				if(!$filter->isEmpty()) {
					$list = $list->alterDataQuery(array($filter, 'apply'));
				}
			}
		}

		$this->extend('updateList', $list);

		return $list;
	}

	public function getManagedModels() {
		$models = $this->stat('managed_models');
		if(is_string($models)) {
			$models = array($models);
		}
		if(!count($models)) {
			user_error(
				'ModelAdmin::getManagedModels(): 
				You need to specify at least one DataObject subclass in public static $managed_models.
				Make sure that this property is defined, and that its visibility is set to "public"', 
				E_USER_ERROR
			);
		}

		// Normalize models to have their model class in array key
		foreach($models as $k => $v) {
			if(is_numeric($k)) {
				if(!singleton($v)->canView() && Member::currentUserID()){
					unset($models[$k]);
					continue;
				}
				$models[$v] = array('title' => singleton($v)->i18n_singular_name());
				unset($models[$k]);
			}
			else{
				if(!singleton($k)->canView() && Member::currentUserID()){
					unset($models[$k]);
					continue;
				}
			}
		}
		
		return $models;
	}
}
?>